<?php

namespace app\admin\controller;

use app\admin\model\Admin;
use app\common\controller\Backend;
use think\db\exception\PDOException;
use think\exception\ValidateException;
use think\facade\Db;

/**
 * 维修记录
 *
 */
class XRepairrecord extends Backend
{
    /**
     * XRepairrecord模型对象
     * @var \app\admin\model\XRepairrecord
     */
    protected $model = null;
    protected $user= null;
    protected $quickSearchField = ['BIZNO'];

    protected $defaultSortField = 'BIZNO,desc';

    protected $preExcludeFields = [''];

    public function initialize()
    {
        parent::initialize();
        $this->model = new \app\admin\model\XRepairrecord;
        $this->user =new Admin();
    }
    protected $noNeedLogin      = ['*'];

    /**
     * 报价
     */
    public function index()
    {
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->param('select')) {
            $this->select();
        }

        $status='';
        list($where, $alias, $limit, $order) = $this->queryBuilder();
        foreach ($where as $k=>$item) {
            if(in_array('x_repairrecord.statuss',$item)){
                $status=" dbo.f_getflowstatus(BIZNO) = '$item[2]'";
                unset($where[$k]);
            }
        }
        $m='';
        $adminInfo          = $this->auth->getInfo();
        if(empty($where)){
            $m="dbo.f_getflowstatus(BIZNO) != '已完成'";
        }
        $res = $this->model
            ->field(['x_repairrecord.*,dbo.f_getflowstatus(BIZNO) as statuss,DEPARTMENT.DEPTNAME'])
            ->join('DEPARTMENT',"x_repairrecord.DEPT=DEPARTMENT.DEPTID",'left')
            ->withJoin($this->withJoinTable, $this->withJoinType)
            ->alias($alias)
            ->where($status)
            ->where($where)
//            ->where($m)
            ->where('x_repairrecord.OP',$adminInfo['nickname'])
            ->order($order)
            ->paginate($limit);

        $this->success('', [
            'list'   => $res->items(),
            'total'  => $res->total(),
            'remark' => get_route_remark(),
        ]);
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (!$data) {
                $this->error(__('Parameter %s can not be empty', ['']));
            }

            $data = $this->excludeFields($data);
            if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                $data[$this->dataLimitField] = $this->auth->id;
            }
            $adminInfo          = $this->auth->getInfo();
            $data['OP']=$adminInfo['nickname'];
            $data['DEPT']=isset($data['DEPT'])?$data['DEPT']:$adminInfo['department'];
            $data['OPTIME']=date('Y-m-d H:i:s',time());
            $data['BIZNO']='MR'. $this->microtime_format('YmdHisx',$this->microtime_float());
            $result = false;
            Db::startTrans();
            try {
                // 模型验证
                if ($this->modelValidate) {
                    $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    if (class_exists($validate)) {
                        $validate = new $validate;
                        if ($this->modelSceneValidate) $validate->scene('add');
                        $validate->check($data);
                    }
                }
                $result = $this->model->save($data);
                Db::commit();
            } catch (ValidateException|PDOException|Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success(__('Added successfully'),  $this->model->BIZNO);
            } else {
                $this->error(__('No rows were added'));
            }
        }

        $this->error(__('Parameter error'));
    }
    /**
     * 编辑
     */
    public function edit()
    {
        $id  = $this->request->param($this->model->getPk());
        $row = $this->model->field('*,dbo.f_getflowstatus(BIZNO) as statuss')->find($id);
        if (!$row) {
            $this->error(__('Record not found'));
        }

        $dataLimitAdminIds = $this->getDataLimitAdminIds();
        if ($dataLimitAdminIds && !in_array($row[$this->dataLimitField], $dataLimitAdminIds)) {
            $this->error(__('You have no permission'));
        }

        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (!$data) {
                $this->error(__('Parameter %s can not be empty', ['']));
            }

            $data   = $this->excludeFields($data);
            $result = false;
            Db::startTrans();
            try {
                // 模型验证
                if ($this->modelValidate) {
                    $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    if (class_exists($validate)) {
                        $validate = new $validate;
                        if ($this->modelSceneValidate) $validate->scene('edit');
                        $validate->check($data);
                    }
                }
                $result = $row->save($data);
                Db::commit();
            } catch (ValidateException|PDOException|Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success(__('Update successful'));
            } else {
                $this->error(__('No rows updated'));
            }

        }

        $this->success('', [
            'row' => $row
        ]);
    }
    /**
     * 报价里的提交核价
     */
    public function evaluation(){
        $id=$this->request->get('BIZNO');
        $up=$this->model->where('BIZNO',$id)->save(['TJFLAG'=>1]);
        if($up){
            $this->success('提交成功');
        }else{
            $this->error('失败');
        }
    }
    /**
     * 核价
     */
    public function index_h()
    {
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->param('select')) {
            $this->select();
        }

        $status='';
        list($where, $alias, $limit, $order) = $this->queryBuilder();

        $adminInfo          = $this->auth->getInfo();

        $res = $this->model
            ->field(['x_repairrecord.*,dbo.f_getflowstatus(BIZNO) as statuss,DEPARTMENT.DEPTNAME'])
            ->join('DEPARTMENT',"x_repairrecord.DEPT=DEPARTMENT.DEPTID",'left')
            ->withJoin($this->withJoinTable, $this->withJoinType)
            ->alias($alias)
            ->where($status)
            ->where($where)
            ->where('TJFLAG','1')
            ->where('x_repairrecord.OP',$adminInfo['nickname'])
            ->order($order)
//            ->fetchSql()->select();
            ->paginate($limit);
//var_dump($res);die;
        $this->success('', [
            'list'   => $res->items(),
            'total'  => $res->total(),
            'remark' => get_route_remark(),
        ]);
    }
    /**
     * 核价修改
     */
    public function edit_h()
    {
        $id  = $this->request->param($this->model->getPk());
        $row = $this->model->field('*,dbo.f_getflowstatus(BIZNO) as statuss')->find($id);
        if (!$row) {
            $this->error(__('Record not found'));
        }

        $dataLimitAdminIds = $this->getDataLimitAdminIds();
        if ($dataLimitAdminIds && !in_array($row[$this->dataLimitField], $dataLimitAdminIds)) {
            $this->error(__('You have no permission'));
        }

        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (!$data) {
                $this->error(__('Parameter %s can not be empty', ['']));
            }

            $data   = $this->excludeFields($data);
            $result = false;
            Db::startTrans();
            try {
                // 模型验证
                if ($this->modelValidate) {
                    $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    if (class_exists($validate)) {
                        $validate = new $validate;
                        if ($this->modelSceneValidate) $validate->scene('edit');
                        $validate->check($data);
                    }
                }
                $result = $row->save($data);
                Db::commit();
            } catch (ValidateException|PDOException|Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success(__('Update successful'));
            } else {
                $this->error(__('No rows updated'));
            }

        }

        $this->success('', [
            'row' => $row,
            'status'=>   $this->status($row->BIZNO),
        ]);
    }
    /**
     * 报价提交审批
     */
    public function tj(){
        $post=$this->request->post();
        $adminInfo          = $this->auth->getInfo();
            //查出录入人部门
            $head=$this->model->where('BIZNO',$post['BIZNO'])->value('OP');
            $dep=$this->user->where('nickname',$head)->value('department');
            $data=[
              'PF'=>$adminInfo['nickname'],
                'PFTIME'=>date("Y-m-d",time()),
                'MONEY'=>$post['MONEY'],
                'PFDEMO'=>isset($post['PFDEMO'])?$post['PFDEMO']:'',
                'YWY'=>$post['YWY'],
                'ZWTYPE'=>$post['ZWTYPE']
            ];
            $this->model->where('BIZNO',$post['bizno'])->save($data);
            $s= $this->createflowdata($post['BIZNO'],$dep,'维修审批',$post['MONEY']);
            if($s==200){
                $this->success('提交成功');
            }else{
                $this->error('提交失败');
            }

    }

    /**
     * 业务确认
     */
    public function index_yw(){


        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->param('select')) {
            $this->select();
        }

        list($where, $alias, $limit, $order) = $this->queryBuilder();
        $status='';
        foreach ($where as $k=>$item) {
            if(in_array('x_repairrecord.statuss',$item)){
                $status=" dbo.f_getflowstatus(BIZNO) = '$item[2]'";
                unset($where[$k]);
            }
        }
        $adminInfo          = $this->auth->getInfo();
        $res = $this->model
            ->field(['x_repairrecord.*,dbo.f_getflowstatus(BIZNO) as statuss,DEPARTMENT.DEPTNAME'])
            ->join('DEPARTMENT',"x_repairrecord.DEPT=DEPARTMENT.DEPTID",'left')
            ->withJoin($this->withJoinTable, $this->withJoinType)
            ->alias($alias)
            ->where($where)
            ->where($status)
            ->where(['ywy'=>$adminInfo['nickname']])
            ->order($order)
//            ->fetchSql()->select();
            ->paginate($limit);
//var_dump($res);die;
        $this->success('', [
            'list'   => $res->items(),
            'total'  => $res->total(),
            'remark' => get_route_remark(),
        ]);
    }
    /**
     * 核价修改
     */
    public function edit_yw()
    {
        $id  = $this->request->param($this->model->getPk());
        $row = $this->model->field('*,dbo.f_getflowstatus(BIZNO) as statuss')->find($id);
        if (!$row) {
            $this->error(__('Record not found'));
        }

        $dataLimitAdminIds = $this->getDataLimitAdminIds();
        if ($dataLimitAdminIds && !in_array($row[$this->dataLimitField], $dataLimitAdminIds)) {
            $this->error(__('You have no permission'));
        }

        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (!$data) {
                $this->error(__('Parameter %s can not be empty', ['']));
            }

            $data   = $this->excludeFields($data);
            $result = false;
            Db::startTrans();
            try {
                // 模型验证
                if ($this->modelValidate) {
                    $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    if (class_exists($validate)) {
                        $validate = new $validate;
                        if ($this->modelSceneValidate) $validate->scene('edit');
                        $validate->check($data);
                    }
                }
                $result = $row->save($data);
                Db::commit();
            } catch (ValidateException|PDOException|Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success(__('Update successful'));
            } else {
                $this->error(__('No rows updated'));
            }

        }

        $this->success('', [
            'row' => $row,
            'status'=>   $this->status($row->BIZNO),
        ]);
    }
    /**
     * 审批
     */
    public function index_s()
    {
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->param('select')) {
            $this->select();
        }

        $status='';
        list($where, $alias, $limit, $order) = $this->queryBuilder();
        foreach ($where as $k=>$item) {
            if(in_array('x_repairrecord.statuss',$item)){
                $status=" dbo.f_getflowstatus(BIZNO) = '$item[2]'";
                unset($where[$k]);
            }
        }
        $m='';
        $adminInfo          = $this->auth->getInfo();
        if($adminInfo['id']!=1){
            if(empty($where)){
                $m="dbo.f_getflowstatus(BIZNO) != '已完成' and exists ( select * from u_flowdata where u_flowdata.bizno=x_repairrecord.BIZNO   and iscurrent=1 and username='$adminInfo[nickname]') ";
            }
            else{
                $m="exists ( select * from u_flowdata where u_flowdata.bizno=x_repairrecord.BIZNO    and username='$adminInfo[nickname]') ";
            }
        }

        $res = $this->model
//            ->field(['*'])
            ->field(['x_repairrecord.*,dbo.f_getflowstatus(BIZNO) as statuss,DEPARTMENT.DEPTNAME'])
            ->join('DEPARTMENT',"x_repairrecord.DEPT=DEPARTMENT.DEPTID",'left')
            ->withJoin($this->withJoinTable, $this->withJoinType)
            ->alias($alias)
            ->where($status)
            ->where($where)
            ->where($m)
//            ->where('x_repairrecord.OP','=',$adminInfo['nickname'])
//            ->order($order)
            ->paginate($limit);

        $this->success('', [
            'list'   => $res->items(),
            'total'  => $res->total(),
            'remark' => get_route_remark(),
        ]);
    }
}